/*
 * Copyright (C) 2008-2009 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.example.android.softkeyboard;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.inputmethodservice.Keyboard;
import android.inputmethodservice.KeyboardView;
import android.inputmethodservice.Keyboard.Key;
import android.util.AttributeSet;
import android.view.View;

public class LatinKeyboardView extends KeyboardView {

    static final int KEYCODE_OPTIONS = -100;
	private SensorManager sm;
	LatinKeyboardView alias = this;

    public LatinKeyboardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        sm = (SensorManager)this.getContext().getSystemService(Context.SENSOR_SERVICE);
    }

    public LatinKeyboardView(Context context, AttributeSet attrs, int defStyle) {    	
        super(context, attrs, defStyle);
        sm = (SensorManager)this.getContext().getSystemService(Context.SENSOR_SERVICE);
    }

    @Override
    protected boolean onLongPress(Key key) {
        if (key.codes[0] == Keyboard.KEYCODE_CANCEL) {
            getOnKeyboardActionListener().onKey(KEYCODE_OPTIONS, null);
            return true;
        } else {
            return super.onLongPress(key);
        }
    }
    
    @Override
    protected void  onWindowVisibilityChanged  (int visibility)
    {
    	if (View.VISIBLE == visibility) {
    		sm.registerListener(listener, sm.getDefaultSensor(Sensor.TYPE_ORIENTATION), sm.SENSOR_DELAY_GAME);
    	} else {
    		sm.unregisterListener(listener);
    	}
    }

	private static long lastTimestamp = 0;
	private static float lastX = 0;
	final private static long THRESHOLD = 100000; // 100ms
    
	private SensorEventListener listener = new SensorEventListener() {

		public void onAccuracyChanged(Sensor sensor, int accuracy) {
			// TODO Auto-generated method stub
		}
		
		public void onSensorChanged(SensorEvent event) {
			if (event != null && event.timestamp-lastTimestamp>THRESHOLD) {
				if (Sensor.TYPE_ORIENTATION==event.sensor.getType()) {					
					float x = event.values[2];
					
					if (Math.abs(x - lastX)>3) {
						if (x < -20.0) {x = -20;}
						if (x > 20.0) {x = 20;}
						float toX = 500*(x+20)/40;
						alias.scrollTo(Math.round(toX), 0);		
					}
					lastX = x;
					lastTimestamp = event.timestamp;
				}
			}			
		}
		
	};
    
}
